package com.lhhu.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lhhu.demo.bean.UserInfo;
import com.lhhu.demo.utils.HttpClientUtil;
import com.lhhu.demo.utils.JavaWebToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther 虎
 * @Data 2021/3/14 13:25
 * @Version 1.0
 */
@RestController
public class WeChatLogin {
    @Autowired
    private UserController userController;

    @GetMapping("/weChatLogin")
    public UserInfo weChatLogin(String code,String avatarUrl, String nickName,String gender){
        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> requestUrlParam = new HashMap<>();
        requestUrlParam.put("appid", "wx4e189359a153d412");
        requestUrlParam.put("secret", "d319f4701fe9846427a0ad4b55e5d8b7");
        requestUrlParam.put("js_code", code);
        requestUrlParam.put("grant_type", "authorization_code");
        JSONObject jsonObject = JSON.parseObject(HttpClientUtil.doPost(requestUrl, requestUrlParam));

        UserInfo userInfo = new UserInfo();
        userInfo.setOpenid(jsonObject.get("openid").toString());
        userInfo.setAvatarUrl(avatarUrl);
        userInfo.setNickName(nickName);
        userInfo.setGender(gender);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("openid",jsonObject.get("openid").toString());
        String token = JavaWebToken.createJavaWebToken(map);
        userInfo.setToken(token);
        if(userController.selectUserByOpenid(userInfo.getOpenid()).isEmpty()) userController.addOneUser(userInfo);
        return userInfo;
    }
}
